<?php

declare(strict_types=1);

namespace app\controller\system\product;

use app\BaseController;
use app\model\ProductImportJob;
use app\model\OrgMember;
use app\service\factory\ResponseFactory;
use think\Response;
use Throwable;

class ImportJob extends BaseController
{
    public function index(): Response
    {
        try {
            $page = max(1, (int) $this->request->param('page', 1));
            $pageSize = (int) $this->request->param('page_size', 20);
            $pageSize = $pageSize > 0 ? min($pageSize, 100) : 20;

            $sellerOrgId = $this->resolveSellerOrgId();

            $query = ProductImportJob::order('id', 'desc');
            if ($sellerOrgId) {
                $query->where('seller_org_id', $sellerOrgId);
            }

            $status = $this->request->param('status');
            if ($status) {
                $query->where('status', (string) $status);
            }

            $paginator = $query->paginate([
                'page' => $page,
                'list_rows' => $pageSize,
            ]);

            $list = array_map([$this, 'formatJob'], $paginator->items());

            return json(ResponseFactory::paginated(
                $list,
                (int) $paginator->total(),
                $page,
                $pageSize
            ));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }

    public function read(int $id): Response
    {
        try {
            /** @var ProductImportJob|null $job */
            $job = ProductImportJob::find($id);
            if (!$job) {
                return json(ResponseFactory::error('任务不存在', 404));
            }

            $sellerOrgId = $this->resolveSellerOrgId();
            if ($sellerOrgId && (int) $job->seller_org_id !== $sellerOrgId) {
                return json(ResponseFactory::error('无权查看该任务', 403));
            }

            return json(ResponseFactory::success($this->formatJob($job, true)));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }

    private function formatJob(ProductImportJob $job, bool $withErrors = false): array
    {
        $data = [
            'id' => (int) $job->id,
            'seller_org_id' => (int) $job->seller_org_id,
            'seller_user_id' => $job->seller_user_id ? (int) $job->seller_user_id : null,
            'status' => $job->status,
            'total_rows' => (int) $job->total_rows,
            'success_count' => (int) $job->success_count,
            'fail_count' => (int) $job->fail_count,
            'chunk_size' => (int) $job->chunk_size,
            'current_index' => (int) $job->current_index,
            'created_at' => $job->create_time,
            'started_at' => $job->started_at,
            'finished_at' => $job->finished_at,
        ];

        if ($withErrors) {
            $data['error_log'] = $job->error_log ?? [];
        }

        return $data;
    }

    private function resolveSellerOrgId(): ?int
    {
        $payload = (array) ($this->request->payload ?? []);
        $groups = $payload['groups'] ?? [];
        if (is_array($groups)) {
            foreach ($groups as $group) {
                if (is_string($group) && strncmp($group, 'seller_', 7) === 0) {
                    $orgId = (int) substr($group, 7);
                    if ($orgId > 0) {
                        return $orgId;
                    }
                }
            }
        }

        $userId = (int) ($this->request->user_id ?? 0);
        if ($userId <= 0) {
            return null;
        }

        $member = OrgMember::where('user_id', $userId)
            ->where('status', 1)
            ->find();

        return $member ? (int) $member->org_id : null;
    }
}
